package com.suxin.algorithm.stack;

import java.util.Arrays;

/**
 * @author Tang
 * @classname MyStackByArray
 * @description [ 基于数组-实现栈 https://blog.csdn.net/weixin_43533825/article/details/96708590 ]
 * @date 2022/4/6 14:26
 */
public class MyStackByArray<T> {

    /**
     * 栈实现的数组
     */
    private Object[] stack;

    /**
     * 数组大小
     */
    private int size;

    public MyStackByArray(int capacity) {
        stack = new Object[capacity];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 入栈
     * @param data
     */
    public void push(T data) {
        // 考虑扩容
        if (this.size >= stack.length) {
            stack = Arrays.copyOf(stack, (int) (stack.length * 1.5));
        }
        stack[size++] = data;
    }

    /**
     * 出栈
     * @return
     */
    public T pop() {
        if (size <= 0) {
            return null;
        }
        T date = (T) stack[--size];
        // 必须清除，防止内存泄漏
        stack[size] = null;
        return date;
    }

    /**
     * 返回栈顶
     * @return
     */
    public T peek() {
        if (size <= 0) {
            return null;
        }
        return (T) stack[size-1];
    }

    public static void main(String[] args) {

        MyStackByArray<String> stack = new MyStackByArray<>(10);
        System.out.println(stack.peek());
        System.out.println(stack.pop());

        stack.push("1");
        stack.push("2");
        stack.push("3");

        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.peek());
    }

}